package com.layton.PubSub;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer_PubSub1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置连接参数
        factory.setHost("127.0.0.1");//默认值为localhost
        factory.setPort(5672);//默认值为5672
        factory.setVirtualHost("/layton");//虚拟机默认为/
        factory.setUsername("layton");//guest
        factory.setPassword("layton");//guest
        //3.获取对应连接connection
        Connection connection = factory.newConnection();
        //4.创建channel
        Channel channel = connection.createChannel();

        String queue1Name = "test_fanout_queue1";
        String queue2Name = "test_fanout_queue2";

        //6.收消息
        Consumer consumer = new DefaultConsumer(channel) {
            //回调方法,当收到消息后会自动执行该方法
            /**
             * @param consumerTag 标识
             * @param envelope 获取一些信息,交换机,路由key
             * @param properties 配置信息
             * @param body 真实的数据
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumerTag = " + consumerTag);
                System.out.println("envelopeExchange = " + envelope.getExchange());
                System.out.println("envelopeRoutingKey = " + envelope.getRoutingKey());
                System.out.println("properties = " + properties);
                System.out.println("body = " + new String(body));
                System.out.println("将日志信息打印到控制台");
            }
        };
        channel.basicConsume(queue1Name,true,consumer);
        //7.不要释放资源
    }
}
